using Godot;
using System;
using Godot.Collections;
using System.Security.Cryptography;

public partial class SaveLoadManager : Node2D
{
	public const string SAVE_PATH = "user://scp_data.sav";
	private Player _player;
	private Dictionary<string, Variant> _loadData;
	public Dictionary<string, Variant> LoadData{get =>_loadData;}
	public override void _Ready()
	{
		var Game = GetNode<Game>("/root/Game");
		_player = Game.get_player();
		_loadData = Load();
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
	}

    public override void _Notification(int what)
    {
        if(what == NotificationWMCloseRequest)
		{
			DelateSavedFile();
		}
    }

    public void DelateSavedFile()
	{
		if(!FileAccess.FileExists(SAVE_PATH))
		{return;}

		var savedFile = FileAccess.Open(SAVE_PATH,FileAccess.ModeFlags.Read);
		var absolutefilepath = savedFile.GetPathAbsolute();
		savedFile.Dispose();

		System.IO.File.Delete(absolutefilepath);
	}

	public void Save()
	{
		var dataForSave = new Dictionary<string, Variant>();

		var savedFileForWrite = FileAccess.Open(SAVE_PATH ,FileAccess.ModeFlags.Write);

		var playerDataForSave = _player.GetDataForSave();

		dataForSave["player"] = playerDataForSave;

		savedFileForWrite.StoreVar(dataForSave);
	}

	private Dictionary<string ,Variant> Load()
	{
		var Game = GetNode<Game>("/root/Game");
		if(!FileAccess.FileExists(SAVE_PATH)){
			Game.InitAllGameData();
			return null;}

		var savedFile = FileAccess.Open(SAVE_PATH,FileAccess.ModeFlags.Read);

		if(savedFile.GetLength() ==0)
		{
			savedFile.Dispose();
			return null;
		}

		var loadData = savedFile.GetVar().AsGodotDictionary<string,Variant>();

		savedFile.Dispose();
		return loadData;
	}
}
